#include "bg_partsys.h"
#include "bg_scene.h"
#include "part2d/part2d_cache.h"

#include "script/scripthelper.h"
#include "script/write_lua.h"
#include "graphics/graphics.h"

#include "util/timer.h"				// log
#include "util/log.h"				// log
#include "util/common_macros.h"		// macros
#include "util/mmgr.h"		    

#include <cassert>
#include <algorithm>

using namespace background;
using namespace script;


BGPartSys::BGPartSys(BGScene*	pScene) : 
	BGElement(pScene),
	m_pSystem(NULL)
{
	m_Size = math::Vec2(0.1f, 0.1f);
	m_Type = ELEMENT_PARTSYS;
}
BGPartSys::~BGPartSys()
{
	//UTIL_SAFE_DELETE(m_pSystem);
	RELEASE_PART(m_pSystem);
}
void	BGPartSys::Render(const math::Vec2& Offset, float Scale) 
{
	if (m_pSystem)
	{
		m_pSystem->SetPos(GetScreenPos(Offset, Scale));
		m_pSystem->Render(Offset, Scale);
	}
}
void	BGPartSys::Tick(float dt)
{
	if (m_pSystem)
	{
		m_pSystem->Tick(dt);
		m_pSystem->SetPos(GetScreenPos(m_pScene->GetOffset(), m_pScene->GetScale()));
		m_pSystem->TickCreation(dt, m_Pos, m_Size);
		m_ClipSize = m_Size;
		// generate particles as well?
	}
	BGElement::Tick(dt);
}

void	BGPartSys::SetPartSys(const std::string& File)
{
	m_PartSys = File;
	//UTIL_SAFE_DELETE(m_pSystem);
	RELEASE_PART(m_pSystem);

	//m_pSystem = new part2d::Part2D();
	//m_pSystem->Load(File);
	m_pSystem = PART_CACHE().GetPart(File);

}

void	BGPartSys::Load(LuaPlus::LuaObject& Obj)
{
	BGElement::Load(Obj);
	m_PartSys = ScriptHelper::GetTableString(Obj, "PartSys");
	SetPartSys(m_PartSys);
}

void	BGPartSys::Save(script::WriteLua* pWL)
{
	BGElement::Save(pWL);
	pWL->WritePair("PartSys", m_PartSys);
}

void	BGPartSys::OnElementReset()
{
	if (m_pSystem) m_pSystem->Clear();
}
